package com.ywx.yypicturebackend.manager.upload;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.ywx.yypicturebackend.constant.FileConstant;
import com.ywx.yypicturebackend.exception.BusinessException;
import com.ywx.yypicturebackend.exception.ErrorCode;
import com.ywx.yypicturebackend.exception.ThrowUtils;
import org.springframework.stereotype.Service;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;

@Service
public class UrlPictureUpload extends PictureUploadTemplate {
    @Override
    protected void processFile(Object inputSource, File file) {
        String fileUrl = (String) inputSource;
        //下载文件
        HttpUtil.downloadFile(fileUrl, file);
    }

    @Override
    protected String getOriginalFilename(Object inputSource) {
        String fileUrl = (String) inputSource;
        String name = FileUtil.getName(fileUrl);

        if(name.contains("?")){
            name = name.substring(0, name.indexOf("?"));
        }
        return name;
    }

    @Override
    protected void validPicture(Object inputSource) {
        String fileUrl = (String) inputSource;
        ThrowUtils.throwIf(StrUtil.isBlank(fileUrl), ErrorCode.PARAMS_ERROR, "文件地址不能为空");

        try {
            //1.验证URL格式
            new URL(fileUrl);//如果不是合法的URL则会报错
        } catch (MalformedURLException e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件地址格式不正确");
        }


        //2.校验URL协议
        ThrowUtils.throwIf(!(fileUrl.startsWith("http://") || fileUrl.startsWith("https://")),
                ErrorCode.PARAMS_ERROR, "仅支持HTTP或HTTPS协议的文件地址");

        //3.发送HEAD请求验证是否存在,但要注意,不是所有图片URL都支持HEAD请求,所有请求失败不用直接抛出异常
        HttpResponse response = null;

        try {
            response = HttpUtil.createRequest(Method.HEAD, fileUrl).execute();

            //如果没有正常响应,无需进行其他判断了,仅对能获取到的信息校验
            if (response.getStatus() != HttpStatus.HTTP_OK) {
                return;
            }
            //如果正常响应
            //4.检验文件类型
            String contentType = response.header("Content-Type");
            if (StrUtil.isNotBlank(contentType)) {
                boolean contains = FileConstant.ALLOW_CONTENT_TYPES.contains(contentType.toLowerCase());
                ThrowUtils.throwIf(!contains, ErrorCode.PARAMS_ERROR, "不支持该文件类型");
            }

            //5.检验文件大小
            String contentLengthStr = response.header("Content-Length");
            if (StrUtil.isNotBlank(contentLengthStr)) {
                try {
                    long contentLength = Long.parseLong(contentLengthStr);

                    ThrowUtils.throwIf(contentLength > FileConstant.MAX_FILE_SIZE * FileConstant.ONE_M,
                            ErrorCode.PARAMS_ERROR, String.format("文件大小不能超过%s%s", FileConstant.MAX_FILE_SIZE, "MB"));
                } catch (NumberFormatException e) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件大小格式错误");
                }

            }

        } finally {
            //最终都要关闭响应
            if (response != null)
                response.close();
        }


    }
}
